<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试结果分析 - 管理员端</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .sidebar-footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 20px;
            border-top: 1px solid var(--border-color);
        }

        .logout-btn {
            width: 100%;
            padding: 12px 16px;
            background: var(--error-color);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: #c82333;
            transform: translateY(-1px);
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin: 0;
        }

        .page-subtitle {
            font-size: 14px;
            color: #666;
            margin: 5px 0 0 0;
        }

        .page-actions {
            display: flex;
            gap: 10px;
        }

        .back-btn {
            background: var(--neutral-light);
            color: var(--neutral-dark);
            border: 1px solid var(--border-color);
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .back-btn:hover {
            background: var(--neutral-medium);
            transform: translateY(-1px);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            text-align: center;
            transition: transform 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-2px);
        }

        .stat-icon {
            font-size: 2.5em;
            margin-bottom: 12px;
            opacity: 0.8;
        }

        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: var(--teacher-color);
            margin-bottom: 8px;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
            font-weight: 500;
        }

        .results-section {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: var(--shadow);
        }

        .section-title {
            font-size: 18px;
            color: var(--neutral-dark);
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
        }

        .filters-bar {
            background: #f8f9fa;
            padding: 16px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .filters-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-label {
            font-size: 12px;
            color: #666;
            font-weight: 500;
        }

        .filter-select {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            background: white;
            min-width: 120px;
        }

        .btn-export {
            background: var(--success-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .btn-export:hover {
            background: #218838;
            transform: translateY(-1px);
        }

        .results-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background: white;
            border-radius: 6px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .results-table th,
        .results-table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid var(--border-color);
        }

        .results-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: var(--neutral-dark);
            font-size: 14px;
        }

        .results-table tr:hover {
            background: #f8f9fa;
        }

        .results-table tr:last-child td {
            border-bottom: none;
        }

        .score-excellent {
            color: var(--success-color);
            font-weight: 600;
        }

        .score-good {
            color: var(--info-color);
            font-weight: 600;
        }

        .score-average {
            color: var(--warning-color);
            font-weight: 600;
        }

        .score-poor {
            color: var(--error-color);
            font-weight: 600;
        }

        .btn-detail {
            background: var(--teacher-color);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .btn-detail:hover {
            background: #4a5bb5;
            transform: translateY(-1px);
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-icon {
            font-size: 3em;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 18px;
            margin-bottom: 8px;
            color: var(--neutral-dark);
            font-weight: 600;
        }

        .empty-description {
            font-size: 14px;
            line-height: 1.5;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }

        .loading-spinner {
            display: inline-block;
            width: 32px;
            height: 32px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--teacher-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .grade-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .grade-excellent {
            background: rgba(76, 175, 80, 0.1);
            color: var(--success-color);
        }

        .grade-good {
            background: rgba(33, 150, 243, 0.1);
            color: var(--info-color);
        }

        .grade-average {
            background: rgba(255, 193, 7, 0.1);
            color: var(--warning-color);
        }

        .grade-poor {
            background: rgba(244, 67, 54, 0.1);
            color: var(--error-color);
        }

        .advanced-search-panel {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 16px;
            margin-bottom: 20px;
            display: none;
        }

        .advanced-search-panel.show {
            display: block;
        }

        .search-row {
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
        }

        .search-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .search-input {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            min-width: 150px;
        }

        .btn-search {
            background: var(--teacher-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-search:hover {
            background: #4a5bb5;
        }

        .btn-clear {
            background: var(--neutral-light);
            color: var(--neutral-dark);
            border: 1px solid var(--border-color);
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-clear:hover {
            background: var(--neutral-medium);
        }

        .view-toggle {
            display: flex;
            gap: 5px;
            margin-left: auto;
        }

        .view-btn {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .view-btn:first-child {
            border-radius: 4px 0 0 4px;
        }

        .view-btn:last-child {
            border-radius: 0 4px 4px 0;
        }

        .view-btn.active {
            background: var(--teacher-color);
            color: white;
            border-color: var(--teacher-color);
        }

        .results-grid {
            display: none;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .results-grid.show {
            display: grid;
        }

        .result-card {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
            transition: transform 0.3s ease;
        }

        .result-card:hover {
            transform: translateY(-2px);
        }

        .result-header {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .student-name {
            font-size: 16px;
            font-weight: 600;
            color: var(--neutral-dark);
            margin-bottom: 4px;
        }

        .student-id {
            font-size: 12px;
            color: #666;
        }

        .result-body {
            padding: 16px;
        }

        .score-display {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
        }

        .score-number {
            font-size: 24px;
            font-weight: bold;
        }

        .score-percentage {
            font-size: 14px;
            color: #666;
        }

        .result-meta {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
            color: #666;
            margin-bottom: 12px;
        }

        .result-actions {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
        }

        .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            color: var(--neutral-dark);
            font-size: 18px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-close:hover {
            color: var(--error-color);
        }

        .modal-body {
            padding: 20px;
        }

        .student-info {
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 6px;
        }

        .student-info h4 {
            margin: 0 0 10px 0;
            color: var(--neutral-dark);
            font-size: 16px;
        }

        .student-info p {
            margin: 5px 0;
            font-size: 14px;
            color: #666;
        }

        .score-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }

        .score-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 4px;
        }

        .score-label {
            font-size: 14px;
            color: #666;
        }

        .score-value {
            font-size: 14px;
            font-weight: 600;
            color: var(--neutral-dark);
        }

        .score-value.grade-score-excellent {
            color: var(--success-color);
        }

        .score-value.grade-score-good {
            color: var(--info-color);
        }

        .score-value.grade-score-average {
            color: var(--warning-color);
        }

        .score-value.grade-score-poor {
            color: var(--error-color);
        }

        .modal-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: var(--teacher-color);
            color: white;
        }

        .btn-primary:hover {
            background: #4a5bb5;
        }

        .btn-secondary {
            background: var(--neutral-light);
            color: var(--neutral-dark);
            border: 1px solid var(--border-color);
        }

        .btn-secondary:hover {
            background: var(--neutral-medium);
        }

        /* 答题详情模态框样式 */
        .answers-modal {
            max-width: 800px;
            width: 95%;
        }

        .exam-summary {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 6px;
        }

        .summary-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex: 1;
        }

        .summary-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }

        .summary-value {
            font-size: 18px;
            font-weight: bold;
            color: var(--teacher-color);
        }

        .answers-container {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }

        .answer-item {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 6px;
            border: 1px solid var(--border-color);
        }

        .answer-item.correct {
            background: rgba(76, 175, 80, 0.05);
            border-color: var(--success-color);
        }

        .answer-item.incorrect {
            background: rgba(244, 67, 54, 0.05);
            border-color: var(--error-color);
        }

        .answer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .question-number {
            font-weight: bold;
            color: var(--neutral-dark);
        }

        .answer-status {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .answer-status.correct {
            background: rgba(76, 175, 80, 0.1);
            color: var(--success-color);
        }

        .answer-status.incorrect {
            background: rgba(244, 67, 54, 0.1);
            color: var(--error-color);
        }

        .question-content {
            margin-bottom: 15px;
        }

        .question-text {
            font-size: 14px;
            color: var(--neutral-dark);
            margin-bottom: 10px;
            line-height: 1.5;
        }

        .answer-options {
            display: grid;
            gap: 5px;
        }

        .option {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            font-size: 13px;
            color: #666;
        }

        .option-label {
            font-weight: 600;
            min-width: 20px;
        }

        .option-text {
            flex: 1;
            line-height: 1.4;
        }

        .answer-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            padding-top: 10px;
            border-top: 1px solid var(--border-color);
        }

        .answer-info {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .info-label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
        }

        .student-answer {
            font-size: 14px;
            color: var(--neutral-dark);
            font-weight: 600;
        }

        .correct-answer {
            font-size: 14px;
            color: var(--success-color);
            font-weight: 600;
        }

        @media (max-width: 768px) {
            .filters-row {
                flex-direction: column;
                align-items: stretch;
            }
            
            .page-header {
                flex-direction: column;
                gap: 15px;
                align-items: stretch;
            }
            
            .results-grid {
                grid-template-columns: 1fr;
            }

            .container {
                margin-left: 0;
                padding: 10px;
            }

            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .score-info {
                grid-template-columns: 1fr;
            }

            .exam-summary {
                flex-direction: column;
                gap: 10px;
            }

            .answer-details {
                grid-template-columns: 1fr;
            }

            .answers-modal {
                width: 98%;
                max-height: 90vh;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <h3>管理员工作台</h3>
        </div>
        <ul class="sidebar-nav">
            <li class="nav-item">
                <a href="dashboard.html" class="nav-link">
                    <i>📊</i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a href="users.html" class="nav-link">
                    <i>👥</i> 用户管理
                </a>
            </li>
            <li class="nav-item">
                <a href="videos.html" class="nav-link">
                    <i>🎥</i> 视频管理
                </a>
            </li>
            <li class="nav-item">
                <a href="pending-videos.html" class="nav-link">
                    <i>📹</i> 待审核视频
                </a>
            </li>
            <li class="nav-item">
                <a href="exam-management.html" class="nav-link active">
                    <i>📝</i> 考试管理
                </a>
            </li>
            <li class="nav-item">
                <a href="profile.html" class="nav-link">
                    <i>👤</i> 个人资料
                </a>
            </li>
        </ul>
        
        <!-- 退出登录 -->
        <div class="sidebar-footer">
            <button class="logout-btn" onclick="UserManager.logout()">
                <i>🚪</i> 退出登录
            </button>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
        <div class="content-wrapper">
            <div class="container">
        <div class="page-header">
            <div>
                <h1 class="page-title">📊 考试结果分析</h1>
                <p class="page-subtitle" id="examTitle">加载中...</p>
            </div>
            <div class="page-actions">
                <button class="back-btn" onclick="goBack()">
                    <span>←</span>
                    <span>返回</span>
                </button>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="stats-grid" id="statsGrid" style="display: none;">
            <div class="stat-card">
                <div class="stat-icon">👥</div>
                <div class="stat-number" id="totalStudents">0</div>
                <div class="stat-label">参与学生</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📊</div>
                <div class="stat-number" id="avgScore">0</div>
                <div class="stat-label">平均分</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">🏆</div>
                <div class="stat-number" id="highestScore">0</div>
                <div class="stat-label">最高分</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">📈</div>
                <div class="stat-number" id="passRate">0%</div>
                <div class="stat-label">及格率</div>
            </div>
        </div>

        <!-- 考试结果列表 -->
        <div class="results-section">
            <div class="section-title">
                <span>📋 学生答题记录</span>
                <div class="view-toggle">
                    <button class="view-btn active" onclick="toggleView('table')">📊 表格</button>
                    <button class="view-btn" onclick="toggleView('grid')">🎯 卡片</button>
                </div>
            </div>
            
            <div class="filters-bar">
                <div class="filters-row">
                    <div class="filter-group">
                        <label class="filter-label">成绩筛选</label>
                        <select class="filter-select" id="gradeFilter" onchange="filterResults()">
                            <option value="">全部成绩</option>
                            <option value="excellent">优秀 (90-100)</option>
                            <option value="good">良好 (80-89)</option>
                            <option value="average">及格 (60-79)</option>
                            <option value="poor">不及格 (0-59)</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">排序方式</label>
                        <select class="filter-select" id="sortFilter" onchange="sortResults()">
                            <option value="score-desc">分数降序</option>
                            <option value="score-asc">分数升序</option>
                            <option value="time-desc">时间降序</option>
                            <option value="time-asc">时间升序</option>
                            <option value="name-asc">姓名升序</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">操作</label>
                        <div style="display: flex; gap: 8px;">
                            <button class="btn-export" onclick="exportResults()">
                                <span>📥</span>
                                <span>导出</span>
                            </button>
                            <button class="btn-clear" onclick="toggleAdvancedSearch()">
                                <span>🔍</span>
                                <span>高级搜索</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 高级搜索面板 -->
            <div class="advanced-search-panel" id="advancedSearchPanel">
                <div class="search-row">
                    <div class="search-group">
                        <label class="filter-label">学生姓名</label>
                        <input type="text" class="search-input" id="studentNameSearch" placeholder="输入学生姓名">
                    </div>
                    <div class="search-group">
                        <label class="filter-label">分数范围</label>
                        <div style="display: flex; gap: 8px; align-items: center;">
                            <input type="number" class="search-input" id="minScore" placeholder="最低分" style="min-width: 80px;">
                            <span>-</span>
                            <input type="number" class="search-input" id="maxScore" placeholder="最高分" style="min-width: 80px;">
                        </div>
                    </div>
                    <div class="search-group">
                        <label class="filter-label">操作</label>
                        <div style="display: flex; gap: 8px;">
                            <button class="btn-search" onclick="performAdvancedSearch()">搜索</button>
                            <button class="btn-clear" onclick="clearAdvancedSearch()">清空</button>
                        </div>
                    </div>
                </div>
            </div>

            <div id="loadingState" class="loading">
                <div class="loading-spinner"></div>
                <p>正在加载考试结果...</p>
            </div>

            <!-- 表格视图 -->
            <div id="resultsTable" class="results-table-container">
                <table class="results-table">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>得分</th>
                            <th>总题数</th>
                            <th>正确率</th>
                            <th>等级</th>
                            <th>考试时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="resultsBody">
                        <!-- 结果数据将在这里动态生成 -->
                    </tbody>
                </table>
            </div>

            <!-- 卡片视图 -->
            <div id="resultsGrid" class="results-grid">
                <!-- 卡片数据将在这里动态生成 -->
            </div>

            <div id="emptyState" class="empty-state" style="display: none;">
                <div class="empty-icon">📊</div>
                <h3 class="empty-title">暂无考试结果</h3>
                <p class="empty-description">还没有学生参加这个考试</p>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let examId = null;
        let examResults = [];
        let allResults = [];
        let currentView = 'table';
        let advancedSearchActive = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            getExamIdFromUrl();
            // 初始化时隐藏loading状态
            document.getElementById('loadingState').style.display = 'none';
            loadExamResults();
        });

        // 检查用户认证状态
        function checkAuth() {
            const user = UserManager.getCurrentUser();
            if (!user || user.role !== 0) {
                Message.error('请先登录管理员账号');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 1500);
                return;
            }
            // 更新用户信息显示（如果存在userInfo元素）
            const userInfoElement = document.getElementById('userInfo');
            if (userInfoElement) {
                userInfoElement.textContent = `欢迎，${user.name}`;
            }
        }

        // 从URL获取考试ID
        function getExamIdFromUrl() {
            const urlParams = new URLSearchParams(window.location.search);
            examId = urlParams.get('examId');
            if (!examId) {
                Message.error('考试ID不存在');
                setTimeout(() => {
                    goBack();
                }, 1500);
            }
        }

        // 加载考试结果
        async function loadExamResults() {
            if (!examId) return;

            try {
                // 显示loading状态
                document.getElementById('loadingState').style.display = 'block';
                document.getElementById('resultsTable').style.display = 'none';
                document.getElementById('resultsGrid').style.display = 'none';
                document.getElementById('emptyState').style.display = 'none';
                
                console.log('开始加载考试结果，examId:', examId);
                const response = await API.get(`/exam/teacher/answers/${examId}`);
                console.log('API响应:', response);
                
                if (response.success) {
                    examResults = response.records || [];
                    allResults = [...examResults];
                    
                    console.log('考试结果数据:', examResults);
                    
                    // 获取考试信息
                    const examResponse = await API.get(`/exam/${examId}`);
                    if (examResponse.success && examResponse.exam) {
                        document.getElementById('examTitle').textContent = examResponse.exam.title;
                    }
                    
                    renderStats();
                    renderResults();
                } else {
                    console.error('API返回失败:', response.message);
                    Message.error(response.message || '加载考试结果失败');
                    showEmptyState();
                }
            } catch (error) {
                console.error('加载考试结果失败:', error);
                Message.error('加载考试结果失败，请稍后重试');
                showEmptyState();
            }
        }

        // 渲染统计信息
        function renderStats() {
            if (examResults.length === 0) {
                document.getElementById('statsGrid').style.display = 'none';
                return;
            }

            const totalStudents = examResults.length;
            const totalScore = examResults.reduce((sum, result) => sum + (result.score || 0), 0);
            const avgScore = totalStudents > 0 ? Math.round(totalScore / totalStudents) : 0;
            const highestScore = Math.max(...examResults.map(result => result.score || 0));
            const passCount = examResults.filter(result => (result.score || 0) >= 60).length;
            const passRate = totalStudents > 0 ? Math.round((passCount / totalStudents) * 100) : 0;

            document.getElementById('totalStudents').textContent = totalStudents;
            document.getElementById('avgScore').textContent = avgScore;
            document.getElementById('highestScore').textContent = highestScore;
            document.getElementById('passRate').textContent = passRate + '%';

            document.getElementById('statsGrid').style.display = 'grid';
        }

        // 渲染结果列表
        function renderResults() {
            const resultsBody = document.getElementById('resultsBody');
            const resultsGrid = document.getElementById('resultsGrid');
            const loadingState = document.getElementById('loadingState');
            const emptyState = document.getElementById('emptyState');
            const resultsTable = document.getElementById('resultsTable');

            loadingState.style.display = 'none';

            console.log('渲染结果列表，数据长度:', examResults.length);
            console.log('结果数据:', examResults);

            if (examResults.length === 0) {
                showEmptyState();
                return;
            }

            // 渲染表格视图
            resultsBody.innerHTML = examResults.map(result => {
                const percentage = result.totalQuestions > 0 ? 
                    Math.round((result.score / result.totalQuestions) * 100) : 0;
                const gradeClass = getGradeClass(percentage);
                const gradeText = getGradeText(percentage);

                console.log('渲染结果项:', result);

                return `
                    <tr>
                        <td>${result.studentName || '未知学生'}</td>
                        <td class="${gradeClass}">${result.score || 0}</td>
                        <td>${result.totalQuestions || 0}</td>
                        <td>${percentage}%</td>
                        <td><span class="grade-badge ${gradeClass}">${gradeText}</span></td>
                        <td>${formatDate(result.examTime)}</td>
                        <td>
                            <button class="btn-detail btn-sm" onclick="viewStudentDetail(${result.studentId})">
                                查看详情
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');

            // 渲染卡片视图
            resultsGrid.innerHTML = examResults.map(result => {
                const percentage = result.totalQuestions > 0 ? 
                    Math.round((result.score / result.totalQuestions) * 100) : 0;
                const gradeClass = getGradeClass(percentage);
                const gradeText = getGradeText(percentage);

                return `
                    <div class="result-card">
                        <div class="result-header">
                            <div class="student-name">${result.studentName || '未知学生'}</div>
                            <div class="student-id">ID: ${result.studentId}</div>
                        </div>
                        <div class="result-body">
                            <div class="score-display">
                                <span class="score-number ${gradeClass}">${result.score || 0}</span>
                                <span class="score-percentage">${percentage}%</span>
                            </div>
                            <div class="result-meta">
                                <span>总题数: ${result.totalQuestions || 0}</span>
                                <span>${formatDate(result.examTime)}</span>
                            </div>
                            <div class="result-actions">
                                <span class="grade-badge ${gradeClass}">${gradeText}</span>
                                <button class="btn-detail btn-sm" onclick="viewStudentDetail(${result.studentId})">
                                    查看详情
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');

            // 显示当前视图
            if (currentView === 'table') {
                resultsTable.style.display = 'block';
                resultsGrid.style.display = 'none';
            } else {
                resultsTable.style.display = 'none';
                resultsGrid.style.display = 'grid';
            }
        }

        // 显示空状态
        function showEmptyState() {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('resultsTable').style.display = 'none';
            document.getElementById('resultsGrid').style.display = 'none';
            document.getElementById('emptyState').style.display = 'block';
            
            console.log('显示空状态：没有考试结果数据');
        }

        // 切换视图模式
        function toggleView(view) {
            currentView = view;
            
            // 更新按钮状态
            document.querySelectorAll('.view-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.classList.add('active');
            
            // 重新渲染结果
            renderResults();
        }

        // 排序结果
        function sortResults() {
            const sortValue = document.getElementById('sortFilter').value;
            
            examResults.sort((a, b) => {
                switch (sortValue) {
                    case 'score-desc':
                        return (b.score || 0) - (a.score || 0);
                    case 'score-asc':
                        return (a.score || 0) - (b.score || 0);
                    case 'time-desc':
                        return new Date(b.examTime) - new Date(a.examTime);
                    case 'time-asc':
                        return new Date(a.examTime) - new Date(b.examTime);
                    case 'name-asc':
                        return (a.studentName || '').localeCompare(b.studentName || '');
                    default:
                        return 0;
                }
            });
            
            renderResults();
        }

        // 切换高级搜索面板
        function toggleAdvancedSearch() {
            const panel = document.getElementById('advancedSearchPanel');
            advancedSearchActive = !advancedSearchActive;
            
            if (advancedSearchActive) {
                panel.classList.add('show');
            } else {
                panel.classList.remove('show');
                clearAdvancedSearch();
            }
        }

        // 执行高级搜索
        function performAdvancedSearch() {
            const studentName = document.getElementById('studentNameSearch').value.toLowerCase();
            const minScore = parseInt(document.getElementById('minScore').value) || 0;
            const maxScore = parseInt(document.getElementById('maxScore').value) || 100;
            
            examResults = allResults.filter(result => {
                const nameMatch = !studentName || (result.studentName || '').toLowerCase().includes(studentName);
                const scoreMatch = (result.score || 0) >= minScore && (result.score || 0) <= maxScore;
                
                return nameMatch && scoreMatch;
            });
            
            renderResults();
        }

        // 清空高级搜索
        function clearAdvancedSearch() {
            document.getElementById('studentNameSearch').value = '';
            document.getElementById('minScore').value = '';
            document.getElementById('maxScore').value = '';
            
            examResults = [...allResults];
            renderResults();
        }

        // 获取成绩等级样式
        function getGradeClass(percentage) {
            if (percentage >= 90) return 'score-excellent';
            if (percentage >= 80) return 'score-good';
            if (percentage >= 60) return 'score-average';
            return 'score-poor';
        }

        // 获取成绩等级文本
        function getGradeText(percentage) {
            if (percentage >= 90) return '优秀';
            if (percentage >= 80) return '良好';
            if (percentage >= 60) return '及格';
            return '不及格';
        }

        // 过滤结果
        function filterResults() {
            const filter = document.getElementById('gradeFilter').value;
            
            if (!filter) {
                examResults = [...allResults];
            } else {
                examResults = allResults.filter(result => {
                    const percentage = result.totalQuestions > 0 ? 
                        Math.round((result.score / result.totalQuestions) * 100) : 0;
                    
                    switch (filter) {
                        case 'excellent': return percentage >= 90;
                        case 'good': return percentage >= 80 && percentage < 90;
                        case 'average': return percentage >= 60 && percentage < 80;
                        case 'poor': return percentage < 60;
                        default: return true;
                    }
                });
            }
            
            // 如果高级搜索是激活状态，需要重新应用高级搜索
            if (advancedSearchActive) {
                performAdvancedSearch();
            } else {
                renderResults();
            }
        }

        // 查看学生答题详情
        function viewStudentDetail(studentId) {
            // 显示学生答题详情模态框
            showStudentDetailModal(studentId);
        }

        // 显示学生答题详情模态框
        function showStudentDetailModal(studentId) {
            const student = examResults.find(result => result.studentId === studentId);
            if (!student) {
                Message.error('未找到学生信息');
                return;
            }

            const percentage = student.totalQuestions > 0 ? 
                Math.round((student.score / student.totalQuestions) * 100) : 0;
            const gradeText = getGradeText(percentage);

            const modalHtml = `
                <div class="modal-overlay" onclick="closeStudentDetailModal()">
                    <div class="modal-content" onclick="event.stopPropagation()">
                        <div class="modal-header">
                            <h3>学生答题详情</h3>
                            <button class="modal-close" onclick="closeStudentDetailModal()">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="student-info">
                                <h4>${student.studentName || '未知学生'}</h4>
                                <p><strong>学生ID:</strong> ${student.studentId}</p>
                                <p><strong>考试时间:</strong> ${formatDate(student.examTime)}</p>
                            </div>
                            <div class="score-info">
                                <div class="score-item">
                                    <span class="score-label">得分:</span>
                                    <span class="score-value">${student.score}</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">总题数:</span>
                                    <span class="score-value">${student.totalQuestions}</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">正确率:</span>
                                    <span class="score-value">${percentage}%</span>
                                </div>
                                <div class="score-item">
                                    <span class="score-label">等级:</span>
                                    <span class="score-value grade-${getGradeClass(percentage)}">${gradeText}</span>
                                </div>
                            </div>
                            <div class="modal-actions">
                                <button class="btn btn-primary" onclick="viewStudentAnswers(${studentId})">查看完整作答</button>
                                <button class="btn btn-primary" onclick="exportStudentResult(${studentId})">导出成绩单</button>
                                <button class="btn btn-secondary" onclick="closeStudentDetailModal()">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        // 关闭学生详情模态框
        function closeStudentDetailModal() {
            const modal = document.querySelector('.modal-overlay');
            if (modal) {
                modal.remove();
            }
        }

        // 查看学生完整作答
        async function viewStudentAnswers(studentId) {
            try {
                // 先关闭当前的学生详情模态框
                closeStudentDetailModal();
                
                const response = await API.get(`/exam/teacher/answers/${examId}`);
                if (response.success) {
                    // 过滤出当前学生的答题记录
                    const studentAnswers = response.answers.filter(answer => answer.studentId === studentId);
                    const studentRecord = response.records.find(record => record.studentId === studentId);
                    
                    // 进一步过滤出学生实际回答的题目（非空答案）
                    const answeredQuestions = studentAnswers.filter(answer => 
                        answer.studentAnswer && answer.studentAnswer.trim() !== ''
                    );
                    
                    if (answeredQuestions.length > 0 && studentRecord) {
                        showStudentAnswersModal(answeredQuestions, studentRecord);
                    } else {
                        Message.warning('该学生没有答题记录');
                    }
                } else {
                    Message.error(response.message || '获取答题详情失败');
                }
            } catch (error) {
                console.error('获取答题详情失败:', error);
                Message.error('获取答题详情失败，请稍后重试');
            }
        }

        // 显示学生答题详情模态框
        function showStudentAnswersModal(answers, record) {
            // 从answers中获取studentId，因为record可能不包含这个字段
            const studentId = answers.length > 0 ? answers[0].studentId : null;
            const student = examResults.find(result => result.studentId === studentId);
            const studentName = student ? student.studentName : '未知学生';

            const answersHtml = answers.map((answer, index) => {
                const isCorrect = answer.isCorrect;
                const correctClass = isCorrect ? 'correct' : 'incorrect';
                const correctText = isCorrect ? '正确' : '错误';
                const correctIcon = isCorrect ? '✅' : '❌';

                return `
                    <div class="answer-item ${correctClass}">
                        <div class="answer-header">
                            <span class="question-number">第${index + 1}题</span>
                            <span class="answer-status ${correctClass}">
                                ${correctIcon} ${correctText}
                            </span>
                        </div>
                        <div class="question-content">
                            <div class="question-text">${answer.questionContent || '题目内容'}</div>
                            <div class="answer-options">
                                <div class="option">
                                    <span class="option-label">A.</span>
                                    <span class="option-text">${answer.optionA || ''}</span>
                                </div>
                                <div class="option">
                                    <span class="option-label">B.</span>
                                    <span class="option-text">${answer.optionB || ''}</span>
                                </div>
                                <div class="option">
                                    <span class="option-label">C.</span>
                                    <span class="option-text">${answer.optionC || ''}</span>
                                </div>
                                <div class="option">
                                    <span class="option-label">D.</span>
                                    <span class="option-text">${answer.optionD || ''}</span>
                                </div>
                            </div>
                        </div>
                        <div class="answer-details">
                            <div class="answer-info">
                                <span class="info-label">学生答案:</span>
                                <span class="student-answer">${answer.studentAnswer || '未作答'}</span>
                            </div>
                            <div class="answer-info">
                                <span class="info-label">正确答案:</span>
                                <span class="correct-answer">${answer.correctAnswer || ''}</span>
                            </div>
                        </div>
                    </div>
                `;
            }).join('');

            const modalHtml = `
                <div class="modal-overlay" onclick="closeStudentAnswersModal()">
                    <div class="modal-content answers-modal" onclick="event.stopPropagation()">
                        <div class="modal-header">
                            <h3>${studentName} - 完整答题详情</h3>
                            <button class="modal-close" onclick="closeStudentAnswersModal()">&times;</button>
                        </div>
                        <div class="modal-body">
                            <div class="exam-summary">
                                <div class="summary-item">
                                    <span class="summary-label">总题数:</span>
                                    <span class="summary-value">${record.totalQuestions}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">得分:</span>
                                    <span class="summary-value">${record.score}</span>
                                </div>
                                <div class="summary-item">
                                    <span class="summary-label">正确率:</span>
                                    <span class="summary-value">${Math.round((record.score / record.totalQuestions) * 100)}%</span>
                                </div>
                            </div>
                            <div class="answers-container">
                                ${answersHtml}
                            </div>
                            <div class="modal-actions">
                                <button class="btn btn-primary" onclick="exportStudentAnswers(${studentId})">导出答题详情</button>
                                <button class="btn btn-secondary" onclick="closeStudentAnswersModal()">关闭</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            document.body.insertAdjacentHTML('beforeend', modalHtml);
        }

        // 关闭学生答题详情模态框
        function closeStudentAnswersModal() {
            const answersModal = document.querySelector('.answers-modal');
            if (answersModal) {
                const modal = answersModal.closest('.modal-overlay');
                if (modal) {
                    modal.remove();
                }
            }
        }

        // 导出学生答题详情
        async function exportStudentAnswers(studentId) {
            try {
                const response = await API.get(`/exam/teacher/answers/${examId}`);
                if (response.success) {
                    // 过滤出当前学生的答题记录
                    const studentAnswers = response.answers.filter(answer => answer.studentId === studentId);
                    const studentRecord = response.records.find(record => record.studentId === studentId);
                    const student = examResults.find(result => result.studentId === studentId);
                    
                    if (studentAnswers.length > 0 && studentRecord && student) {
                        // 创建CSV内容，添加BOM头以支持中文显示
                        let csvContent = '\uFEFF' + "题目,题目内容,选项A,选项B,选项C,选项D,学生答案,正确答案,是否正确\n";
                        
                        studentAnswers.forEach((answer, index) => {
                            const isCorrect = answer.isCorrect ? '正确' : '错误';
                            csvContent += `第${index + 1}题,"${answer.questionContent || ''}","${answer.optionA || ''}","${answer.optionB || ''}","${answer.optionC || ''}","${answer.optionD || ''}","${answer.studentAnswer || '未作答'}","${answer.correctAnswer || ''}","${isCorrect}"\n`;
                        });
                        
                        // 添加学生基本信息
                        const percentage = studentRecord.totalQuestions > 0 ? 
                            Math.round((studentRecord.score / studentRecord.totalQuestions) * 100) : 0;
                        const gradeText = getGradeText(percentage);
                        
                        csvContent += `\n学生信息\n`;
                        csvContent += `学生姓名,${student.studentName || '未知学生'}\n`;
                        csvContent += `学生ID,${studentId}\n`;
                        csvContent += `得分,${studentRecord.score}\n`;
                        csvContent += `总题数,${studentRecord.totalQuestions}\n`;
                        csvContent += `正确率,${percentage}%\n`;
                        csvContent += `等级,${gradeText}\n`;
                        csvContent += `考试时间,${formatDate(studentRecord.examTime)}\n`;
                        
                        // 下载文件
                        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                        const link = document.createElement('a');
                        const url = URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', `学生答题详情_${student.studentName}_${new Date().toISOString().split('T')[0]}.csv`);
                        link.style.visibility = 'hidden';
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        
                        Message.success('答题详情导出成功');
                    } else {
                        Message.warning('未找到该学生的答题记录');
                    }
                } else {
                    Message.error(response.message || '获取答题详情失败');
                }
            } catch (error) {
                console.error('导出答题详情失败:', error);
                Message.error('导出答题详情失败，请稍后重试');
            }
        }

        // 导出学生成绩单
        function exportStudentResult(studentId) {
            const student = examResults.find(result => result.studentId === studentId);
            if (!student) {
                Message.error('未找到学生信息');
                return;
            }

            const percentage = student.totalQuestions > 0 ? 
                Math.round((student.score / student.totalQuestions) * 100) : 0;
            const gradeText = getGradeText(percentage);

            // 添加BOM头以支持中文显示
            const csvContent = '\uFEFF' + `学生姓名,学生ID,得分,总题数,正确率,等级,考试时间\n${student.studentName || '未知学生'},${student.studentId},${student.score},${student.totalQuestions},${percentage}%,${gradeText},${formatDate(student.examTime)}`;

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `学生成绩单_${student.studentName}_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            Message.success('成绩单导出成功');
        }

        // 导出结果
        function exportResults() {
            if (examResults.length === 0) {
                Message.warning('没有数据可以导出');
                return;
            }

            // 创建CSV内容，添加BOM头以支持中文显示
            let csvContent = '\uFEFF' + "学生姓名,得分,总题数,正确率,等级,考试时间\n";
            examResults.forEach(result => {
                const percentage = result.totalQuestions > 0 ? 
                    Math.round((result.score / result.totalQuestions) * 100) : 0;
                const gradeText = getGradeText(percentage);
                const examTime = formatDate(result.examTime);
                
                csvContent += `${result.studentName || '未知学生'},${result.score},${result.totalQuestions},${percentage}%,${gradeText},${examTime}\n`;
            });

            // 下载文件
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `考试结果_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            Message.success('导出成功');
        }

        // 返回上一页
        function goBack() {
            window.location.href = 'exam-management.html';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '未知';
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                UserManager.logout();
                window.location.href = '../login.html';
            }
        }
    </script>

    <!-- 侧边栏切换按钮 -->
    <button class="sidebar-toggle">☰</button>
        </div>
    </div>
</body>
</html>
